package com.pwrd.tank;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;
import java.util.Random;

public class NetClient {
	
	private static int UDP_PORT = (int) (2223 + Math.random()*1000);
//	private static int UDP_PORT = 2223 + new Random().nextInt(1000);
	private int udpPort;
	TankClient tc;
	
	DatagramSocket ds = null;
	
	public NetClient(TankClient tc) {
		udpPort = UDP_PORT ;
		this.tc = tc ;
		try {
			ds = new DatagramSocket(UDP_PORT);
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 客户端tcp连接服务器
	 * @param ip 服务器ip
	 * @param port 服务器tcp端口
     */
    public void connect(String ip, int port) {
		Socket s = null;
		try {
			s = new Socket(ip, port);
			DataOutputStream dos = new DataOutputStream(s.getOutputStream());
			dos.writeInt(udpPort);
			DataInputStream dis = new DataInputStream(s.getInputStream());
			int uid = dis.readInt();
			tc.myTank.id = uid;
			if(uid % 2 == 0) {
				tc.myTank.good = false;
			}else {
				tc.myTank.good = true;
			}

System.out.println("Connect to IP adress = " + s.getInetAddress() + " and port = " + s.getPort());
		} catch (UnknownHostException e) {	
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(s != null ) {
				try {
					s.close();	//tcp传输完udp端口号后不再保留
					s = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}	
		}
		
		TankNewMsg msg = new TankNewMsg(tc.myTank);
		send(msg);

		//启动client端的upd数据接收线程
		new Thread(new UDPRecvThread()).start();
	}

	public void send(Msg msg) {
		msg.send(ds, "127.0.0.1", TankServer.UDP_PORT);
	}

	private class UDPRecvThread implements Runnable {

		byte[] buf = new byte[1024];

		@Override
		public void run() {

			System.out.println("client udp recv start！");

			while(ds != null) {
				DatagramPacket dp = new DatagramPacket(buf, buf.length);
				try {
					ds.receive(dp);
					parseUDPMsg(dp);
System.out.println("A package received from server");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		private void parseUDPMsg(DatagramPacket dp) {
			ByteArrayInputStream bais = new ByteArrayInputStream(buf, 0, dp.getLength());
			DataInputStream dis = new DataInputStream(bais);
			int msgType = 0;
			try {
				msgType =  dis.readInt();
			} catch (IOException e) {
				e.printStackTrace();
			}
			Msg msg = null;
			switch (msgType) {
                case Msg.TANK_NEW_MSG:
					msg = new TankNewMsg(NetClient.this.tc); //内部类访问外部类的成员变量
					msg.parse(dis);

					break;
				case Msg.TANK_MOVE_MSG:
					msg = new TankMoveMsg(NetClient.this.tc);
					msg.parse(dis);
					break;
				case Msg.TANK_MISSILE_NEW_MSG:
					msg = new MissileNewMsg(NetClient.this.tc);
					msg.parse(dis);
					break;
				case Msg.TANK_DEAD_MSG:
					msg = new TankDeadMsg(NetClient.this.tc);
					msg.parse(dis);
					break;

			}
		}
	}
}
